package com.adam.example.search;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.HitsMetadata;
import co.elastic.clients.json.JsonData;
import com.adam.example.ElasticsearchClientHolder;
import com.adam.example.types.GeoCityShape;

import java.io.IOException;
import java.util.*;

public class SearchGeoShapeExample {

    public static void main(String[] args) throws IOException {
        ElasticsearchClient client = ElasticsearchClientHolder.getINSTANCE().initializeAndGetClient();

        //按照GeoJSON格式组装polygon多边形数据。
        //GeoJSON中，坐标为[经度,纬度]
        Map<String, Object> geoShapeMap = new HashMap<>();
        geoShapeMap.put("type", "envelope");
        List<List<Double>> coordinatesList = new ArrayList<>();
        coordinatesList.add(Arrays.asList(106.23248, 38.48644));
        coordinatesList.add(Arrays.asList(115.85794, 28.68202));
        geoShapeMap.put("coordinates", coordinatesList);
        SearchRequest searchRequest = SearchRequest.of(builder -> builder
                        .index("test_geo_shape")
                        .query(queryBuilder -> queryBuilder
                                // geo_shape
                                .geoShape(geoShapeQueryBuilder -> geoShapeQueryBuilder
                                        .field("location")
                                        .shape(geoShapeFieldQuerybuilder -> geoShapeFieldQuerybuilder
                                                .shape(JsonData.of(geoShapeMap))
                                        )
                                )
                )
        );

        SearchResponse<GeoCityShape> searchResponse = client.search(searchRequest, GeoCityShape.class);
        HitsMetadata<GeoCityShape> hitsMetadata = searchResponse.hits();
        System.out.println("搜索到" + hitsMetadata.total().value() + "条数据");
        List<Hit<GeoCityShape>> geoCityShapeHitList = hitsMetadata.hits();
        for(int i=0;i<geoCityShapeHitList.size();i++) {
            Hit<GeoCityShape> geoCityShapeHit = geoCityShapeHitList.get(i);
            GeoCityShape geoCityShape = geoCityShapeHit.source();
            System.out.println("文档[" + (i+1) + "][评分" + geoCityShapeHit.score() + "]:" + geoCityShape);
        }

        ElasticsearchClientHolder.getINSTANCE().close();
    }

}
